package org.redmagic.client.location;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.redmagic.api.RedMagicRequestFactory;
import org.redmagic.client.api.Location;
import org.redmagic.client.api.LocationFactory;
import org.redmagic.client.api.RedMagicTransaction;
import org.redmagic.client.utils.DocumentUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class WebLocationFactory implements LocationFactory {

	private static final Log LOG = LogFactory.getLog(WebLocationFactory.class);
	
	private final RedMagicRequestFactory requestFactory;
	
	private final RedMagicTransaction transaction;
	
	public WebLocationFactory(RedMagicRequestFactory requestFactory, RedMagicTransaction transaction) {
		this.requestFactory = requestFactory;
		this.transaction = transaction;
	}
	
	@Override
	public Location createLocation(Element location) {

		String name = location.getAttribute("name");
		WebLocation webLocation = null;
		URI uri = null;
		
		try {
			uri = new URI(location.getAttribute("uri"));
			webLocation = new WebLocation(name, uri, requestFactory, transaction);
		} catch (URISyntaxException e) {

			throw new RuntimeException("Unable to create web location with uri: " + uri);
		}

		// Parse the attempts to create the hierarchy
		NodeList attempts = location.getElementsByTagName("attempt");
		for (int i = 0; i < attempts.getLength(); i++) {
			
			webLocation.addAttempt(DocumentUtils.parseAttempt((Element) attempts.item(i)));
		}
		
		LOG.info(webLocation.getHierarchy());
		
		return webLocation;
	}

}
